
let params = {
  left: 0,
  top: 0,
  currentX: 0,
  currentY: 0,
  flag: false,
};
// 获取相关CSS属性
let getCss = function (o, key) {
  return o.currentStyle ? o.currentStyle[key] : document.defaultView.getComputedStyle(o, false)[key];
};

// 拖拽的实现
export default (bar, target, cb) => {
  if (!process.browser) return;
  if (getCss(target, 'left') !== 'auto') {
    params.left = getCss(target, 'left');
  }
  if (getCss(target, 'top') !== 'auto') {
    params.top = getCss(target, 'top');
  }
  // o是移动对象
  bar.onmousedown = function (event) {
    params.flag = true;
    if (!event) {
      event = window.event;
      // 防止IE文字选中
      bar.onselectstart = function () {
        return false;
      };
    }
    let e = event;
    params.currentX = e.clientX;
    params.currentY = e.clientY;
  };
  document.onmouseup = function () {
    params.flag = false;
    if (getCss(target, 'left') !== 'auto') {
      params.left = getCss(target, 'left');
    }
    if (getCss(target, 'top') !== 'auto') {
      params.top = getCss(target, 'top');
    }
  };
  document.onmousemove = function (event) {
    let e = event || window.event;
    let nowX = e.clientX;
    let nowY = e.clientY;
    let disX = nowX - params.currentX;
    let disY = nowY - params.currentY;
    if (params.flag) {
      target.style.left = parseInt(params.left) + disX + 'px';
      target.style.top = parseInt(params.top) + disY + 'px';
      if (event.preventDefault) {
        event.preventDefault();
      }
      return false;
    }

    if (typeof cb === 'function') {
      let x = parseInt(params.left) + disX;
      let y = parseInt(params.top) + disY;
      cb(x, y);
    }
  };
  // 绑定touchstart事件
  let oW, oH;
  target.addEventListener('touchstart', function (e) {
    let touches = e.touches[0];
    oW = touches.clientX - target.offsetLeft;
    oH = touches.clientY - target.offsetTop;
    // 阻止页面的滑动默认事件
    document.addEventListener('touchmove', () => {}, false);
  }, false);

  target.addEventListener('touchmove', function (e) {
    let touches = e.touches[0];
    let oLeft = touches.clientX - oW;
    let oTop = touches.clientY - oH;
    if (oLeft < 0) {
      oLeft = 0;
    } else if (oLeft > document.documentElement.clientWidth - target.offsetWidth) {
      oLeft = (document.documentElement.clientWidth - target.offsetWidth);
    }
    target.style.left = oLeft + 'px';
    target.style.top = oTop + 'px';
    e.preventDefault();
  }, false);

  target.addEventListener('touchend', function () {
    document.removeEventListener('touchmove', () => {}, false);
  }, false);
};
